import {designComponent, getComponentCls, PropType, reactive, useClassCache} from "@peryl/react-compose";
import {usePageService} from "../../modules/micro/usePageService";
import {iResumeRecord} from "./resume.utils";
import {http} from "../../modules/plain-design/http";
import {$dialog, $loading, $message} from "plain-design";
import './ResumeList.scss';
import {PageCardList} from "../components/PageCardList";
import {iPageCardStarterOption, PageCardStarter} from "../components/PageCardStarter";

export const ResumeList = designComponent({
  name: 'resume-list',
  props: {
    isTemplate: { type: String as PropType<'Y' | 'N'>, required: true },
    starterTitle: { type: String, required: true },
    editText: { type: String, required: true },
    copyText: { type: String, required: true },
    handleEdit: { type: Function as PropType<(resume: iResumeRecord) => void>, required: true },
    starterOptions: { type: Array as PropType<iPageCardStarterOption[]>, required: true }
  },
  setup({ props }) {

    const { nav, onBack } = usePageService();

    const classes = useClassCache(() => [
      getComponentCls('resume-list')
    ]);

    const state = reactive({
      resumeData: [] as iResumeRecord[],
    });

    const handler = {
      reloadData: async () => {
        const closeLoading = $loading();
        try {
          const respData = await http.post<{ list: iResumeRecord[] }>(
            '/resume/list',
            { all: true, filters: [{ field: 'isTemplate', operator: '=', value: props.isTemplate }] }
          );
          state.resumeData = respData.list;
        } finally {
          closeLoading();
        }
      },
      deleteResumeRecord: async (resume: iResumeRecord) => {
        await $dialog.confirm(`确认删除简历${props.isTemplate === 'Y' ? '模板' : ''}？`);
        await http.post('/resume/delete', { id: resume.id });
        await handler.reloadData();
        $message.success('已删除');
      },
      copyResumeRecord: async (resume: iResumeRecord) => {
        await $dialog.confirm(`复制简历${props.isTemplate === 'Y' ? '模板' : ''}？`);
        const { id, createdAt, createdBy, updatedAt, updatedBy, ...newResume } = resume;
        await http.post('/resume/insert', { row: newResume });
        await handler.reloadData();
      },
    };

    handler.reloadData();

    onBack(() => {handler.reloadData();});

    const starter = () => (<PageCardStarter title={props.starterTitle} starterOptions={props.starterOptions}/>);

    return () => (
      <PageCardList
        className={classes.value}
        data={[starter, ...state.resumeData]}
        editButtonText={props.editText}
        copyButtonText={props.copyText}
        showEditButton
        showCopyButton
        showDeleteButton
        onEdit={props.handleEdit}
        onCopy={handler.copyResumeRecord}
        onDelete={handler.deleteResumeRecord}
      />
    );
  },
});
